package com.yixun.qfbao.api.service.impl;

import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.api.service.DataPermissionService;
import com.yixun.qfbao.api.service.DeptPermissionService;
import com.yixun.qfbao.api.service.PersonnelService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.apidto.v10dto.ForgetPwdReqDto;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.*;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.PasswordUtil;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.PremisesService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/11/22.
 * 人员
 */
@Service
public class PersonnelServiceImpl implements PersonnelService {
    private Logger logger = LoggerFactory.getLogger(PersonnelServiceImpl.class);
    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    ValidateCodeMapper validateCodeMapper;
    @Autowired
    PartnerInfoMapper partnerInfoMapper;
    @Autowired
    SMSUtil smsUtil;
    @Autowired
    DictionaryMapper dictionaryMapper;
    @Autowired
    SmsHistoryService smsHistoryService;
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    ChannelRoleMapper channelRoleMapper;
    @Autowired
    CompanyRelationService companyRelationService;
    @Autowired
    PremisesService premisesService;
    @Autowired
    CaseMemberService caseMemberService;
    @Autowired
    ValidateCodeService validateCodeService;
    @Autowired
    UploadExcelService uploadExcelService;
    @Autowired
    DictionaryService dictionaryService;
    @Autowired
    CompanyService companyService;
    @Autowired
    SmsSettingService smsSettingService;
    @Autowired
    PremisesRelationService premisesRelationService;
    @Autowired
    DataPermissionService dataPermissionService;
    @Autowired
    DeptPermissionService deptPermissionService;
    /**
    *@Description 重置密码，校验短信验证码
    *@Author sangtao
    *@Date 2017/11/23
    *@param dto
    **/
    @Override
    public ResetPwdResDto resetPwd(ResetPwdReqDto dto){
        ResetPwdResDto resetPwdResDto = new ResetPwdResDto();
        //验证码
        boolean flag = isValidate(dto.getPhone(),dto.getCode(),dto.getDomain(),dto.getLoginType(),dto.getCompanyUuid());
        //验证成功
        if(flag){
            PartnerInfo user = getPartnerInfo(dto.getDomain(),dto.getPhone(),dto.getCompanyUuid());
            if(user != null){
                RedisUtil.setEx("ForgetPwd:"+dto.getPhone(), dto.getCompanyUuid(), 2, TimeUnit.MINUTES);
                resetPwdResDto.setResult(ResultEnum.SUCCESS.getNo());
                resetPwdResDto.setResultMsg("验证成功");
            }else{
                resetPwdResDto.setResult(ResultEnum.FAIL.getNo());
                resetPwdResDto.setResultMsg("账号不存在或已禁用");
            }
        }else{
            resetPwdResDto.setResult(ResultEnum.FAIL.getNo());
            resetPwdResDto.setResultMsg("验证码错误");
        }
        return resetPwdResDto;
    }

    @Override
    public ResetPwdResDto resetPwdByForget(ResetPwdByForgetReqDto dto) {
        ResetPwdResDto resetPwdResDto = new ResetPwdResDto();
        PartnerInfo user = getPartnerInfo(dto.getDomain(),dto.getPhone(),dto.getCompanyUuid());
        if(user != null){
            PartnerInfoDto editInfo = new PartnerInfoDto();
            editInfo.setId(user.getId());
            editInfo.setPassword(PasswordUtil.md5Hex(dto.getConfirmPassword()));
            partnerInfoService.update(editInfo);
            resetPwdResDto.setResult(ResultEnum.SUCCESS.getNo());
            resetPwdResDto.setResultMsg("密码重置成功");
        }else{
            resetPwdResDto.setResult(ResultEnum.FAIL.getNo());
            resetPwdResDto.setResultMsg("账号不存在或已禁用");
        }
        return resetPwdResDto;
    }

    /**
    *@Description
    *@Author sangtao
    *@Date 2017/11/23
    *@param dto
    **/
    @Override
    public UpdatePwdResDto updatePwd(UpdatePwdReqDto dto){
        UpdatePwdResDto updatePwdResDto = new UpdatePwdResDto();
        PartnerInfo info = partnerInfoMapper.selectById(Long.valueOf(dto.getUserId()));
        if(!PasswordUtil.md5Hex(dto.getOldPassword()).equals(info.getPassword())){
            throw new TServerException("原密码错误");
        }

        if(PasswordUtil.md5Hex(dto.getNewPassword()).equals(info.getPassword())){
            throw new TServerException("新密码不能跟原密码相同");
        }

        if(!dto.getNewPassword().equals(dto.getConfirmPassword())){
            throw new TServerException("新密码不一致");
        }
        PartnerInfoDto infodto=new PartnerInfoDto();
        org.springframework.beans.BeanUtils.copyProperties(info, infodto);
        infodto.setPassword(PasswordUtil.md5Hex(dto.getNewPassword()));
        if(partnerInfoMapper.edit(infodto) <= 0){
            throw new TServerException("修改密码失败");
        }
        //密码修改成功,短信提醒
        //判断短信开发是否开启
      //  String smsSwitch = smsUtil.getSmsSwitch();
        String smsSwitch ="F";//去掉修改密码发送短信功能
        if(org.apache.commons.lang.StringUtils.isNotEmpty(smsSwitch) && "T".equals(smsSwitch)){
            //获取短信模板
            String smsTemp = SMSTypeEnum.TYPE_12.getNo();
            DictionaryDto dicDto = new DictionaryDto();
            dicDto.setDicType(smsTemp);
            Dictionary dic = dictionaryMapper.selectByDto(dicDto);
            if(null != dic){
                String cusName = info.getAccountName();
                String mobile = info.getPhone();
                Long companyId = null;
                String smsContent = dic.getDicValue();
                smsContent = String.format(smsContent, cusName, dto.getNewPassword());
                //获取开发商
                Company company = companyService.selectById(companyId);
                if(null != company && StringUtils.isNotBlank(company.getDomain())) {
                	companyId = company.getId();
                }else {
                	CompanyRelationDto crDto = new CompanyRelationDto();
					crDto.setAgentCompany(companyId);
					crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
					List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
					if(null != crList && crList.size() > 0){
						CompanyRelation cr = crList.get(0);
						companyId = cr.getDevCompany();
					}
                }
                //获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
                Map<String, String> smsSettingMap = null;
//            	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, companyId,null);
                Map<String,String> qfSmsMap = new HashMap<>();
                qfSmsMap.put("key1",cusName);
                qfSmsMap.put("key2",dto.getNewPassword());

                //发送短信
                Map<String, Object> returnMap = smsUtil.sendMessage(smsContent, mobile, QfSmsTemplateEnum.SMS_RESET_PWD.getId(), smsSettingMap,qfSmsMap);
                boolean sendStatus = (Boolean) returnMap.get("sendStatus");
                String sendRes = String.valueOf(returnMap.get("sendRes"));
                //保存短信历史信息
                SmsHistoryDto smsHis = new SmsHistoryDto();
                smsHis.setSender(smsUtil.getUserName());
                if(null != smsSettingMap) {
    				smsHis.setSender(smsSettingMap.get("userName"));
    			}
                smsHis.setReceiver(mobile);
                smsHis.setContent(smsContent);
                smsHis.setSendStatus(sendStatus? SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
                smsHis.setSendRes(sendRes);
                smsHis.setMerchantId(companyId);
                smsHis.setRemark("修改密码: 用户修改密码");
                smsHis.setCreateUserId(info.getId());
                if(returnMap.containsKey("orderUuid")){
                    smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
                }
                if(returnMap.containsKey("platform")){
                    smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
                }
                smsHistoryService.create(smsHis);
            }
        }
        updatePwdResDto.setResult(ResultEnum.SUCCESS.getNo());
        return updatePwdResDto;

    }

    /**
     *@Description
     *@Author sangtao
     *@Date 2017/11/23
     *@param dto
     **/
    @Override
    public AddPartnerResDto addPartner(AddPartnerReqDto dto){
        AddPartnerResDto addPartnerResDto =new AddPartnerResDto();
        PartnerInfo partnerInfo = new PartnerInfo();
        // 管理员账号,不允许创建
        if("18888888888".equals(dto.getPhone())){
            addPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            addPartnerResDto.setResultMsg("无效账号: 188-8888-8888");
            return addPartnerResDto;
        }
        //手机号码是否已存在（正在启用的）
        List<PartnerInfo> partners = partnerInfoService.getRegisterPartnerByCondition(dto.getDomain(),dto.getPhone(),dto.getCompanyUuid());
        if(partnerInfo != null && partners.size() > 0){
            addPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            addPartnerResDto.setResultMsg("手机号已存在");
            return addPartnerResDto;
        }
        org.springframework.beans.BeanUtils.copyProperties(dto,partnerInfo);

        //根据部门获取公司id
        Department department = departmentDao.selectById(dto.getDeptId());
        //设置公司id,密码
        partnerInfo.setHigherid(department.getMerchantId());
        partnerInfo.setPassword(PasswordUtil.md5Hex(dto.getPassword()));
        if(StringUtils.isNotEmpty(dto.getUserRoleId())) {
        	partnerInfo.setUserRoleId(Long.valueOf(dto.getUserRoleId()));
        }
        partnerInfo.setCreateTime(Calendar.getInstance().getTime());
        partnerInfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfo.setIsAdmin("0");
        
        if(!StringUtil.isNotNull(partnerInfo.getCheckStatus())) {
			partnerInfo.setCheckStatus(CheckStatusEnum.NOT_REQUIRED.getNo());
		}
        partnerInfoMapper.add(partnerInfo);
        dto.setId(partnerInfo.getId());

        addPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
        addPartnerResDto.setResultMsg("操作成功!");
        return addPartnerResDto;
    }

    /**
     *@Description
     *@Author JHSong
     *@Date 2018-4-23
     *@param dto
     **/
    @Override
    public AddPartnerQuickResDto addPartnerQuick(AddPartnerQuickReqDto dto){
    	AddPartnerQuickResDto resDto =new AddPartnerQuickResDto();
    	resDto.setExistAgent(0);
    	resDto.setAppointAgent(1);
    	resDto.setAgentPhone(dto.getAgentPhone());
        PartnerInfo partnerInfo = new PartnerInfo();
        //手机号码是否已存在（正在启用的）
        List<PartnerInfo> partners = partnerInfoService.getRegisterPartner(dto.getDomain(),dto.getAgentPhone(),dto.getCompanyUuid());

        // 过滤掉开发商
        Company devCompany = getCompanyByDomain(dto.getDomain(), dto.getCompanyUuid());
        if(null != devCompany){
            if(null != partners && partners.size() > 0){
                for(PartnerInfo pi: partners){
                    if(pi.getHigherid().compareTo(devCompany.getId()) == 0){
                        resDto.setResult(ResultEnum.FAIL.getNo());
                        resDto.setResultMsg("添加失败: 该手机号已存在!");
                        return resDto;
                    }
                }
            }
        }

        if(null != partners && partners.size() > 0){
        	partnerInfo = partners.get(0);
        	resDto.setAgentId(String.valueOf(partnerInfo.getId()));
            resDto.setAgentName(partnerInfo.getAccountName());
            resDto.setAgentCompany(String.valueOf(partnerInfo.getHigherid()));
            resDto.setResult(ResultEnum.SUCCESS.getNo());
            Company agentCompany = companyService.selectById(partnerInfo.getHigherid());
            resDto.setCompanyName(agentCompany.getCompanyName());
            //该楼盘是否指定分销商
            PremisesRelationDto pd = new PremisesRelationDto();
            pd.setAgentCompanyId(partnerInfo.getHigherid());
            pd.setDevCompanyId(devCompany.getId());
            pd.setPremisesId(dto.getPremisesId());
            pd.setStatus(RelationStatusEnum.VALID.getNo());
            pd.setDelFlag(DelFlagEnum.UNDEL.getNo());
            List<PremisesRelation> prList = premisesRelationService.selectListByDto(pd);
            if(null == prList || prList.size() == 0){
                resDto.setAppointAgent(0);
            }
            //已存在经纪人
            resDto.setExistAgent(1);
            resDto.setResultMsg("操作成功!");
            return resDto;
        }

        //根据域名获取公司
        Company company = companyService.selectById(Long.valueOf(dto.getAgentCompany()));
        if(null == company) {
        	resDto.setResult(ResultEnum.FAIL.getNo());
        	resDto.setResultMsg("添加失败: 经纪公司不存在");
            return resDto;
        }

        //获取经纪公司的顶级部门
        DepartmentDto deptDto = new DepartmentDto();
        deptDto.setMerchantId(Long.valueOf(dto.getAgentCompany()));
        deptDto.setParentId(0L);
        Department dept = departmentDao.selectByDto(deptDto);
        if(null == dept) {
        	resDto.setResult(ResultEnum.FAIL.getNo());
        	resDto.setResultMsg("添加失败: 经纪公司不存在");
            return resDto;
        }

        PartnerInfoDto piDto = new PartnerInfoDto();
        String password = PasswordUtil.generateRandomPwd(8);
        // 改成固定密码,随机的客户使用有困难: jhsong-2020-10-15
        password = "x1234567";
        piDto.setDeptId(dept.getId());
        piDto.setAccountName(dto.getAgentName());
        piDto.setPhone(dto.getAgentPhone());
        piDto.setPassword(PasswordUtil.md5Hex(password));
        piDto.setAccountType("1");
        piDto.setStatus("1");
        piDto.setHigherid(company.getId());
        piDto.setIsAdmin("0");
        piDto = partnerInfoService.create(piDto);

        piDto = new PartnerInfoDto();
        piDto.setAccountName(dto.getAgentName());
        piDto.setPhone(dto.getAgentPhone());
        PartnerInfo pi = partnerInfoService.selectByDto(piDto);

        resDto.setAgentId(String.valueOf(pi.getId()));
        resDto.setAgentName(pi.getAccountName());
        resDto.setAgentCompany(String.valueOf(pi.getHigherid()));
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setResultMsg("操作成功!新密码为：" + password);
        return resDto;
    }

    /**
     * 编辑人员
     * 同一个手机号在同一个域名系吖不能同时有两个启用的账号
     */
    @Override
    public EditPartnerResDto editPartner(EditPartnerReqDto dto) {
        Long lastUserRoleId = 0L;
        EditPartnerResDto editPartnerResDto = new EditPartnerResDto();
        // 管理员账号,不允许创建
        if("18888888888".equals(dto.getPhone())){
            editPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            editPartnerResDto.setResultMsg("无效账号: 188-8888-8888");
            return editPartnerResDto;
        }

        List<PartnerInfo> partnerInfos = partnerInfoService.getRegisterPartnerByCondition(dto.getDomain(), dto.getPhone(), dto.getCompanyUuid());
        int count = 0;
        if (null != partnerInfos && partnerInfos.size() > 0) {
            count = partnerInfos.size();
        }
        PartnerInfoDto partnerInfo = new PartnerInfoDto();
        org.springframework.beans.BeanUtils.copyProperties(dto, partnerInfo);
        if (StringUtils.isNotEmpty(dto.getUserRoleId())) {
            partnerInfo.setUserRoleId(Long.valueOf(dto.getUserRoleId()));
        } else {
            partnerInfo.setUserRoleId(null);
        }
        partnerInfo.setUpdateTime(Calendar.getInstance().getTime());
        lastUserRoleId = partnerInfo.getUserRoleId();
        if (count == 1 && dto.getId().equals(partnerInfos.get(0).getId())) {
            partnerInfoMapper.edit(partnerInfo);
        } else if (count == 0) {
            partnerInfoMapper.edit(partnerInfo);
        } else if (MechanismStatusEnum.disable.getNo().equals(partnerInfo.getStatus())) {
            partnerInfoMapper.edit(partnerInfo);
        } else {
            //列表不止一条数据，但是可能是同一个人
            boolean flag = true;
            for (PartnerInfo info : partnerInfos) {
                if (!dto.getId().equals(info.getId())) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                partnerInfoMapper.edit(partnerInfo);
            } else {
                editPartnerResDto.setResult(ResultEnum.FAIL.getNo());
                editPartnerResDto.setResultMsg("手机号已存在，请重新输入");
                return editPartnerResDto;
            }
        }
        // 编辑用户清除用户所属公司下所有人员缓存
        // 原因: 会影响到绑定了本部权限的所有人
        dataPermissionService.cleanCompanyCacheByPartner(partnerInfo.getId());

        editPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
        editPartnerResDto.setResultMsg("操作成功");
        return editPartnerResDto;
    }

    /**
     * 删除人员
     *
     */
    @Override
    public DelPartnerResDto delPartner(DelPartnerReqDto dto){
        DelPartnerResDto delPartnerResDto = new DelPartnerResDto();
        if(dto.getUserId().equals(dto.getId().toString())){
            delPartnerResDto.setResultMsg("不能删除自己");
            return delPartnerResDto;
        }
        //查询登陆人是否为管理员
        PartnerInfo loginInfo = partnerInfoMapper.selectById(Long.parseLong(dto.getUserId()));
        if(loginInfo == null || !PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(loginInfo.getAccountType())){
            delPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            delPartnerResDto.setResultMsg("非管理员不能进行删除");
            return delPartnerResDto;
        }
        //删除人员
        try{
            PartnerInfo partnerInfo = partnerInfoService.selectById(dto.getId());
    		if(null == partnerInfo){
    			delPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                delPartnerResDto.setResultMsg("您要删除的用户不存在");
                return delPartnerResDto;
    		}
    		if(!PartnerInfoEnum.STATUS_DISABLE.getCode().equals(partnerInfo.getStatus())){
    			delPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                delPartnerResDto.setResultMsg("请先禁用该用户");
                return delPartnerResDto;
    		}

    		PartnerInfo info = new PartnerInfo();
            info.setId(dto.getId());
            int i = partnerInfoService.deletePartnerInfo(info);
            if(i > 0){
                delPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                delPartnerResDto.setResultMsg("删除成功");
            }else{
                delPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                delPartnerResDto.setResult("删除失败");
            }
        }catch (RuntimeException e){
            logger.error("PersonnelServiceImpl ==> delPartner error: {}", e);
            delPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
            delPartnerResDto.setResultMsg("删除人员失败:" + e.getMessage());
        }
        return delPartnerResDto;
    }

    /**
    *@Description 禁用或启用人员
    *@Author sangtao
    *@Date 2017/11/23
    *@param dto
    **/
    @Override
    public ForbiddenOrNotPartnerResDto forbiddenOrNotPartner(ForbiddenOrNotPartnerReqDto dto){
        ForbiddenOrNotPartnerResDto forbiddenOrNotPartnerResDto = new ForbiddenOrNotPartnerResDto();
        try{
            String status = dto.getStatus();
            if(PartnerInfoEnum.STATUS_DISABLE.getCode().equals(status)){
                status = PartnerInfoEnum.STATUS_ENABLE.getCode();
                PartnerInfo info = partnerInfoMapper.selectById(dto.getId());
                List<PartnerInfo> list = partnerInfoService.getRegisterPartner(dto.getDomain(),info.getPhone(),dto.getCompanyUuid());
                if(list != null && list.size() > 0){
                    forbiddenOrNotPartnerResDto.setResult(ResultEnum.FAIL.getNo());
                    forbiddenOrNotPartnerResDto.setResultMsg("该手机号已存在被启用的用户");
                    return forbiddenOrNotPartnerResDto;
                }
            }else if(PartnerInfoEnum.STATUS_ENABLE.getCode().equals(status)){
                status = PartnerInfoEnum.STATUS_DISABLE.getCode();
            }
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
            partnerInfoDto.setId(dto.getId());
            partnerInfoDto.setStatus(status);
            int i = partnerInfoService.update(partnerInfoDto);
            if(i > 0){
                forbiddenOrNotPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                forbiddenOrNotPartnerResDto.setResultMsg("操作成功");
            }
        }catch (Exception e){
            logger.error("PersonnelServiceImpl ==> forbiddenOrNotPartner error: {}", e);
            forbiddenOrNotPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            forbiddenOrNotPartnerResDto.setResultMsg("操作失败");
        }
        return forbiddenOrNotPartnerResDto;
    }

    /**
     *@Description 获取本部机构人员
     *@Author sangtao
     *@Date 2017/11/23
     *@param reqDto
     **/
    @Override
    public GetDevPartnerPageResDto getDevPartnerPage(GetDevPartnerPageReqDto reqDto){
        GetDevPartnerPageResDto getDevPartnerPageResDto = new GetDevPartnerPageResDto();
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        //从登陆人那里获取公司id(开发商id),拼接查询sql PartnerInfoDto
        PartnerInfo partner = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        partnerInfoDto.setAccountName(reqDto.getAccountName());
        partnerInfoDto.setPhone(reqDto.getPhone());
        partnerInfoDto.setAccountType(reqDto.getAccountType());
        partnerInfoDto.setSearchContent(reqDto.getSearchContent());
        partnerInfoDto.setStatus(reqDto.getStatus());
        List<Long> deptIds = new ArrayList<Long>();
        if(StringUtils.isNotEmpty(reqDto.getDeptIds())) {
        	String[] deptIdsArr = reqDto.getDeptIds().split("[,]");
        	for(int ii=0; ii<deptIdsArr.length; ii++) {
        		deptIds.add(Long.valueOf(deptIdsArr[ii]));
        	}
        }
        partnerInfoDto.setDeptIds(deptIds);
        partnerInfoDto.setHigherid(partner.getHigherid());
        partnerInfoDto.setOrders("status desc, create_time desc");
        partnerInfoDto.setSql("(user_roleId != -1 or user_roleId is null)");
        Page<PartnerInfo> page = new Page<PartnerInfo>();
        //查询总数
        try {
        	int pageNo = reqDto.getPageNo();
        	int pageSize = reqDto.getPageSize();
        	page = partnerInfoService.getPageModel(partnerInfoDto, PageUtil.begin(pageNo, pageSize), pageSize);
        	page.setPageInfo(page.getTotal(), PageUtil.begin(pageNo, pageSize), pageSize * pageNo);
            getDevPartnerPageResDto.setResult(ResultEnum.SUCCESS.getNo());
            getDevPartnerPageResDto.setPage(page);
        }catch (Exception e){
            logger.error("PersonnelServiceImpl ==> getDevPartnerPage error: {}",e);
            getDevPartnerPageResDto.setResult(ResultEnum.FAIL.getNo());
        }
        return getDevPartnerPageResDto;
    }

    /**
     * 设置驻场人员时，查看除超级管理员外的所有成员
     * @param reqDto
     * @return
     */
    public GetDevPartnerPageResDto getDevNewPartnerPage(GetDevPartnerPageReqDto reqDto){
        GetDevPartnerPageResDto getDevPartnerPageResDto = new GetDevPartnerPageResDto();
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        //从登陆人那里获取公司id(开发商id),拼接查询sql PartnerInfoDto
        PartnerInfo partner = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        partnerInfoDto.setAccountName(reqDto.getAccountName());
        partnerInfoDto.setPhone(reqDto.getPhone());
        partnerInfoDto.setAccountType(reqDto.getAccountType());
        partnerInfoDto.setSearchContent(reqDto.getSearchContent());
        partnerInfoDto.setStatus(reqDto.getStatus());
        List<Long> deptIds = new ArrayList<Long>();
        if(StringUtils.isNotEmpty(reqDto.getDeptIds())) {
            String[] deptIdsArr = reqDto.getDeptIds().split("[,]");
            for(int ii=0; ii<deptIdsArr.length; ii++) {
                deptIds.add(Long.valueOf(deptIdsArr[ii]));
            }
        }
        partnerInfoDto.setDeptIds(deptIds);
        partnerInfoDto.setHigherid(partner.getHigherid());
        partnerInfoDto.setOrders("status desc, create_time desc");
        /** 添加sql条件 将超级管理员排除在外 */
        partnerInfoDto.setSql("((user_roleId != -1 or user_roleId is null) and account_type != 0)");
        Page<PartnerInfo> page = new Page<PartnerInfo>();
        //查询总数
        try {
            int pageNo = reqDto.getPageNo();
            int pageSize = reqDto.getPageSize();
            page = partnerInfoService.getPageModel(partnerInfoDto, PageUtil.begin(pageNo, pageSize), pageSize);
            page.setPageInfo(page.getTotal(), PageUtil.begin(pageNo, pageSize), pageSize * pageNo);
            getDevPartnerPageResDto.setResult(ResultEnum.SUCCESS.getNo());
            getDevPartnerPageResDto.setPage(page);
        }catch (Exception e){
            logger.error("PersonnelServiceImpl ==> getDevPartnerPage error: {}",e);
            getDevPartnerPageResDto.setResult(ResultEnum.FAIL.getNo());
        }
        return getDevPartnerPageResDto;
    }

    /**
    *@Description 分销经纪人
    *@Author sangtao
    *@Date 2017/11/23
    *@param dto
    **/
    @Override
    public GetAgentPartnerPageResDto getAgentPartnerPage(GetAgentPartnerPageReqDto dto){
        Boolean btnFlg = false;
        String registerStatus = null;
        Long fristDeptId = 0L;
        GetAgentPartnerPageResDto getAgentPartnerPageResDto = new GetAgentPartnerPageResDto();

        PartnerInfo piLogin = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));

        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        //deptId 是否为空  获取全部还是获取某个
        String deptIds = dto.getDeptIds();
        List<Long> deptIdsList = new ArrayList<Long>();
        if(StringUtils.isNotEmpty(deptIds)) {
        	String[] deptIdsArr = deptIds.split("[,]");
        	for(int ii=0; ii<deptIdsArr.length; ii++) {
        		deptIdsList.add(Long.valueOf(deptIdsArr[ii]));
        	}
            //获取第一个部门id
            fristDeptId = Long.valueOf(deptIdsArr[0]);
        }
        if (fristDeptId != 0L) {
            Department department = departmentDao.selectById(fristDeptId);
            if (department.getParentId() == 0) {
                btnFlg = true;
                Company company = companyService.selectById(department.getMerchantId());
                //存入一级分销机构公司注册功能的启用状态
                getAgentPartnerPageResDto.setRegisterStatus(company.getIfOpenSysMsg());
                getAgentPartnerPageResDto.setAgentCompanyId(company.getId());
            }
        }
        getAgentPartnerPageResDto.setBtnFlg(btnFlg);
        partnerInfoDto.setDeptIds(deptIdsList);
        partnerInfoDto.setPhone(dto.getPhone());
        partnerInfoDto.setAccountName(dto.getAccountName());
        partnerInfoDto.setAccountType(dto.getAccountType());
        partnerInfoDto.setDepartmentName(dto.getDepartmentName());
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setSql("((t.user_roleId != -1 or t.user_roleId is null) and t.check_status in(2, 3))");
        partnerInfoDto.setOrders("status desc,create_time desc");
        Page<PartnerInfoDto> pageModel = new Page<PartnerInfoDto>();
        pageModel.setTotal(0);
        try {
        	//区分管理员及普通经纪人
        	//管理员,可以查看所有合作机构部门下的经纪人
        	//普通经纪人,可以查看自己作为对接人的部门下的经纪人
        	if(PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(piLogin.getAccountType())) {
        		//管理员获取经纪人
        		//1、未选择任何部门时                                                                                                                                                                                         
        		//2、根据合作机构获取所有合作机构下的经纪人
        		if(null == deptIdsList || deptIdsList.size() == 0) {
                	CompanyRelationDto relationDto = new CompanyRelationDto();
                    relationDto.setDevCompany(piLogin.getHigherid());
                    relationDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
                    relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                    List<CompanyRelation> lists = companyRelationService.selectListByDto(relationDto);
                    List<String> higherIds = new ArrayList<String>();
                    for(CompanyRelation relation:lists){
                        higherIds.add(relation.getAgentCompany().toString());
                    }
                  //当普通员工未对接任何部门时,无数据
            		if(null==lists||lists.size() == 0) {
            			getAgentPartnerPageResDto.setPage(pageModel);
            			return getAgentPartnerPageResDto;
            		}
                    if(PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(piLogin.getAccountType())) {
                    	partnerInfoDto.setHigherIds(higherIds);
                    }
        		}
        	}else {
        		//获取所有的对接部门Ids
        		if(null == deptIdsList || deptIdsList.size() == 0) {
        			deptIdsList = getDepartmentIds(piLogin.getHigherid(),piLogin.getId(), deptIdsList);
            		partnerInfoDto.setDeptIds(deptIdsList);
        		}
        		//当普通员工未对接任何部门时,无数据
        		if(deptIdsList.size() == 0) {
        			getAgentPartnerPageResDto.setPage(pageModel);
        			return getAgentPartnerPageResDto;
        		}
        	}
        	pageModel = partnerInfoService.getPageModelByHigherid(partnerInfoDto, PageUtil.begin(dto.getPageNo(), dto.getPageSize()), dto.getPageSize());
            getAgentPartnerPageResDto.setPage(pageModel);
        }catch (YIXUNUNCheckedException e) {
            logger.error("PersonnelServiceImpl ==> getAgentPartnerPage YIXUNUNCheckedException: {}", e);
            getAgentPartnerPageResDto.setResult(ResultEnum.FAIL.getNo());
            getAgentPartnerPageResDto.setResultMsg("分页信息失败");
        }catch (Exception e) {
            logger.error("PersonnelServiceImpl ==> getAgentPartnerPage error: {}",e);
            getAgentPartnerPageResDto.setResult(ResultEnum.FAIL.getNo());
            getAgentPartnerPageResDto.setResultMsg("分页信息失败");
        }
        return getAgentPartnerPageResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetPartnerByCompanyResDto getPartnerByCompany(GetPartnerByCompanyReqDto dto){
        GetPartnerByCompanyResDto getAgentPartnerPageResDto = new GetPartnerByCompanyResDto();
        List<PartnerInfo> partnerInfoList = new ArrayList<PartnerInfo>();
        try {
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
            if(null != dto.getCompanyId()){
                partnerInfoDto.setHigherid(dto.getCompanyId());
                partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                partnerInfoDto.setStatus(MechanismStatusEnum.enable.getNo());
                List<PartnerInfo> list = partnerInfoService.selectListByDto(partnerInfoDto);
                if(list != null && list.size() > 0){
                    for(PartnerInfo partnerInfo : list){
                        PartnerInfo entity = new PartnerInfoDto();
                        entity.setId(partnerInfo.getId());
                        entity.setAccountName(partnerInfo.getAccountName());
                        partnerInfoList.add(entity);
                    }
                }
                getAgentPartnerPageResDto.setPartnerInfoList(partnerInfoList);
            }else {
            	PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(dto.getUserId()));
            	partnerInfoDto.setHigherid(pi.getHigherid());
                List<PartnerInfo> list = partnerInfoService.selectListByDto(partnerInfoDto);
                if(list != null && list.size() > 0){
                    for(PartnerInfo partnerInfo : list){
                        PartnerInfo entity = new PartnerInfoDto();
                        entity.setId(partnerInfo.getId());
                        entity.setAccountName(partnerInfo.getAccountName());
                        partnerInfoList.add(entity);
                    }
                }
                getAgentPartnerPageResDto.setPartnerInfoList(partnerInfoList);
            }

        } catch (Exception e) {
            logger.error("PersonnelServiceImpl ==> getPartnerByCompany error: {}", e);
        }
        return getAgentPartnerPageResDto;
    }

    /**
    *@description 查询楼盘相关驻守经纪人
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetPartnerByPremisesResDto getPartnerByPremises(GetPartnerByPremisesReqDto dto){
        GetPartnerByPremisesResDto getPartnerByPremisesResDto = new GetPartnerByPremisesResDto();
        List<CaseMemberDto> cmList = new ArrayList<CaseMemberDto>();
        try{
            //查询在售楼盘相关驻守经纪人
            CaseMemberDto cmDto = new CaseMemberDto();
            cmDto.setPremisesId(dto.getPremisesId());
            cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
            cmList = caseMemberService.selectParAndPreListByDto(cmDto);

            //查询管理员
            Premises premises = premisesService.selectSimpleById(dto.getPremisesId());
            if(premises != null){
                PartnerInfoDto piDto = new PartnerInfoDto();
                piDto.setHigherid(Long.valueOf(premises.getCompanyId()));
                piDto.setStatus(MechanismStatusEnum.enable.getNo());
                piDto.setAccountType(MechanismAccountTypeEnum.mechanism.getNo());
                List<PartnerInfo> piList = partnerInfoService.selectListByDto(piDto);
                for(PartnerInfo info : piList){
                    CaseMemberDto cm = new CaseMemberDto();
                    cm.setPartnerId(info.getId());
                    cm.setAccountName(info.getAccountName());
                    cmList.add(cm);
                }
            }
            getPartnerByPremisesResDto.setPartnerList(cmList);
            getPartnerByPremisesResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch(Exception ex){
            logger.error("PersonnelServiceImpl ==> getPartnerByPremises error: {}: ", ex);
        }
        return getPartnerByPremisesResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetPartnerByAgentOrgResDto getPartnerByAgentOrg(GetPartnerByAgentOrgReqDto dto){
        GetPartnerByAgentOrgResDto getPartnerByAgentOrgResDto = new GetPartnerByAgentOrgResDto();
        List<PartnerInfo> piList = new ArrayList<PartnerInfo>();
        try{
            //公司下启用的经纪人
            PartnerInfoDto piDto = new PartnerInfoDto();
            piDto.setHigherid(Long.valueOf(dto.getCompanyId()));
            piDto.setStatus(MechanismStatusEnum.enable.getNo());
            piDto.setAccountName(dto.getSearchValue());
            piDto.setOrders("create_time desc");
            piList = partnerInfoService.searchListByDto(piDto,PageUtil.begin(dto.getPageNo(),dto.getPageSize()),dto.getPageSize() * 5);
            getPartnerByAgentOrgResDto.setAgentList(piList);
            getPartnerByAgentOrgResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch(Exception ex){
            logger.error("PersonnelServiceImpl ==> getPartnerByAgentOrg error: {}: ", ex);
        }
        return getPartnerByAgentOrgResDto;
    }

    /**
    *@description 中介公司启用的经纪人数量
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetPartnerCountByAgentOrgResDto getPartnerCountByAgentOrg(GetPartnerCountByAgentOrgReqDto dto){
        GetPartnerCountByAgentOrgResDto getPartnerCountByAgentOrgResDto = new GetPartnerCountByAgentOrgResDto();
        try{
            //公司下启用的经纪人
            PartnerInfoDto piDto = new PartnerInfoDto();
            piDto.setHigherid(Long.valueOf(dto.getCompanyId()));
            piDto.setStatus(MechanismStatusEnum.enable.getNo());
            piDto.setAccountName(dto.getSearchValue());
            Integer count = partnerInfoService.searchListByDtoCount(piDto);
            getPartnerCountByAgentOrgResDto.setResDate(count.toString());
            getPartnerCountByAgentOrgResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch(Exception ex){
            logger.error("PersonnelServiceImpl ==> getPartnerCountByAgentOrg error: {}: ", ex);
        }
        return getPartnerCountByAgentOrgResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetPartnerByDeptResDto getPartnerByDept(GetPartnerByDeptReqDto dto){
        GetPartnerByDeptResDto getPartnerByDeptResDto = new GetPartnerByDeptResDto();
        // 当前登录用户
        PartnerInfo currLoginUser = partnerInfoMapper.selectById(Long.parseLong(dto.getUserId()));

        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setDeptIds(dto.getDeptIds());
        partnerInfoDto.setAccountName(dto.getAccountName());
        partnerInfoDto.setPhone(dto.getPhone());
        partnerInfoDto.setAccountType(dto.getAccountType());
        partnerInfoDto.setHigherid(currLoginUser.getHigherid());
        partnerInfoDto.setOrders("status desc,create_time desc");
        partnerInfoDto.setSql("check_status in(2,3)");
        Page<PartnerInfoDto> partnerInfoPage = partnerInfoService.getDtoPageModel(partnerInfoDto,
                PageUtil.begin(dto.getPageNo(), dto.getPageSize()),dto.getPageSize());
        partnerInfoPage.setPageInfo(partnerInfoPage.getTotal(), PageUtil.begin(dto.getPageNo(), dto.getPageSize()), dto.getPageSize() * dto.getPageNo());
        getPartnerByDeptResDto.setPage(partnerInfoPage);
        return getPartnerByDeptResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/24
    *@param dto
    **/
    @Override
    public GetUserByIdResDto getUserById(GetUserByIdReqDto dto){
        GetUserByIdResDto getUserByIdResDto = new  GetUserByIdResDto();
        PartnerInfo partnerInfo;

        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        if(dto.getId()!=null){
            partnerInfoDto.setId(dto.getId());
        }else if(dto.getUserId() != null){
            partnerInfoDto.setId(Long.valueOf(dto.getUserId()));
        }else{
            getUserByIdResDto.setResult("-2");
            return getUserByIdResDto;
        }

        partnerInfo = partnerInfoService.selectByDto(partnerInfoDto);

        if(partnerInfo == null || partnerInfo.getId() == null){
            getUserByIdResDto.setResult("-2");
            return getUserByIdResDto;
        }
        BeanUtils.copyProperties(partnerInfo,getUserByIdResDto);
        getUserByIdResDto.setResult(ResultEnum.SUCCESS.getNo());
        return getUserByIdResDto;
    }

    /**
     *@description 人员注册
     *@author sangtao
     *@date 2017/11/25
     *@param dto
     **/
    @Override
    public RegisterPartnerResDto registerPartner(RegisterPartnerReqDto dto){
        RegisterPartnerResDto registerPartnerResDto = new RegisterPartnerResDto();
        //验证短信有效性
        if(validateCodeService.isValidate(dto.getPhone(),dto.getVerificationCode())){
            List<PartnerInfo> list = partnerInfoService.getRegisterPartner(dto.getDomain(),dto.getPhone(),dto.getCompanyUuid());
            if(list != null && list.size() > 0){
                registerPartnerResDto.setResult(ResultEnum.FAIL.getNo());
                registerPartnerResDto.setResultMsg("您的帐号已存在，请直接登录");
                return registerPartnerResDto;
            }
            PartnerInfoDto partnerInfo = new PartnerInfoDto();
            BeanUtils.copyProperties(dto,partnerInfo);
            Map<String,String> resultMap = partnerInfoService.bindPartner(partnerInfo,dto.getCompanyUuid());
            if("success".equals(resultMap.get("success"))){
                registerPartnerResDto.setResult(ResultEnum.SUCCESS.getNo());
                registerPartnerResDto.setResultMsg(resultMap.get("msg"));
            }else{
                registerPartnerResDto.setResult(ResultEnum.FAIL.getNo());
                registerPartnerResDto.setResultMsg(resultMap.get("msg"));
            }
        }else{
            registerPartnerResDto.setResult(ResultEnum.FAIL.getNo());
            registerPartnerResDto.setResultMsg("短信验证码错误");
        }
        return registerPartnerResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/25
    *@param dto
    **/
    @Override
    public ImportUserResDto importUser(ImportUserReqDto dto){
        ImportUserResDto importUserResDto = new ImportUserResDto();
        try {
            MultipartFile file = null;
            Iterator<String> fileNames = dto.getMulRequest().getFileNames();
            if (fileNames.hasNext()) {
                String fileName = fileNames.next(); //附件对应的参数名
                if(!isExcel(fileName)){
                    importUserResDto.setResult(ResultEnum.FAIL.getNo());
                    importUserResDto.setResultMsg("请选择正确的excel");
                    return importUserResDto;
                }

                file = dto.getMulRequest().getFile(fileName); // 获取到附件
                if(file == null){
                    importUserResDto.setResult(ResultEnum.FAIL.getNo());
                    importUserResDto.setResultMsg("批量导入失败,请刷新页面后重试");
                    return importUserResDto;
                }
                PartnerInfo currentLoginUser = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
                if("1".equals(dto.getOptType())){
                    //导入机构
                    Map<String,String> resultMap = uploadExcelService.uploadExcel(dto.getParentId(), currentLoginUser, file.getInputStream(), fileName);
                    // 刷新导入机构权限Code及机构层级
                    deptPermissionService.initDeptPermissionCode(currentLoginUser.getHigherid());
                    importUserResDto.setResult(resultMap.get("result"));
                    importUserResDto.setResultMsg(resultMap.get("msg"));
                }else if("2".equals(dto.getOptType())){
                    //导入员工
                    Map<String,String> resultMap = uploadExcelService.uploadExcelUser( Long.parseLong(dto.getUserId()), file.getInputStream(), fileName);
                    importUserResDto.setResult(resultMap.get("result"));
                    importUserResDto.setResultMsg(resultMap.get("msg"));
                }else{
                    importUserResDto.setResult(ResultEnum.FAIL.getNo());
                    importUserResDto.setResultMsg("批量导入失败");
                }
            }
        } catch (Exception e) {
            logger.error("PersonnelServiceImpl ==> importUser error: {}: ", e);
            importUserResDto.setResult(ResultEnum.FAIL.getNo());
            importUserResDto.setResultMsg("批量导入失败");
            return importUserResDto;
        }
        return importUserResDto;

    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/25
    *@param dto
    **/
    @Override
    public ExportPartnerResDto exportPartner(ExportPartnerReqDto dto){
        ExportPartnerResDto resDto = new ExportPartnerResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        //导出不需要限制条数,先设置1万条，不够再加
        Integer pageNo = 1;
        Integer pageSize = 10000;
        PartnerInfoDto entity = new PartnerInfoDto();
        if(null != dto) {
        	BeanUtils.copyProperties(dto,entity);
        }
        Page<PartnerInfoDto> pageModel = new Page<PartnerInfoDto>();
        try {
            if(StringUtils.isNotBlank(dto.getDeptId())){
                Department department = departmentDao.selectById(Long.valueOf(dto.getDeptId()));
                List<Long> deptIds = getDeptIds(department);
                if(deptIds.size()>1){
                    entity.setDeptIds(deptIds);
                    entity.setDeptId(null);
                }
                entity.setHigherid(department.getMerchantId());
                entity.setOrders("create_time desc");
                entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
            //    entity.setStatus(MechanismStatusEnum.enable.getNo());
                pageModel = partnerInfoService.getMyPageModel2(entity, PageUtil.begin(pageNo, pageSize), pageSize);
                pageModel.setPageInfo(pageModel.getTotal(), PageUtil.begin(pageNo, pageSize), pageSize * pageNo);
            }else{
                //一开始显示所有合作机构人员
                PartnerInfo partner = partnerInfoMapper.selectById(Long.parseLong(dto.getUserId()));
                if(partner!=null){
                    CompanyRelationDto relationDto = new CompanyRelationDto();
                    relationDto.setDevCompany(partner.getHigherid());
                    relationDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
                    relationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                    List<CompanyRelation> lists = companyRelationService.selectListByDto(relationDto);
                    List<String> higherIds = new ArrayList<String>();
                    for(CompanyRelation relation:lists){
                        higherIds.add(relation.getAgentCompany().toString());
                    }
                    if(higherIds.size()>0){
                        PartnerInfoDto infoDto = new PartnerInfoDto();
                        infoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                   //     infoDto.setStatus(MechanismStatusEnum.enable.getNo());
                        infoDto.setHigherIds(higherIds);
                        infoDto.setAccountName(entity.getAccountName());
                        infoDto.setPhone(entity.getPhone());
                        infoDto.setDepartmentName(entity.getDepartmentName());
                        infoDto.setAccountType(entity.getAccountType());
                        pageModel = partnerInfoService.getPageModelByHigherid(infoDto,PageUtil.begin(pageNo, pageSize), pageSize);
                        pageModel.setPageInfo(pageModel.getTotal(), PageUtil.begin(pageNo, pageSize), pageSize * pageNo);
                    }
                }
            }
            List<PartnerInfoDto> impList = pageModel.getRows();
            if(impList.size()>0){
                List<String[]> headerList = new ArrayList<String[]>(); //表头
                String[] header = new String[]{"机构名称","员工姓名","手机号","角色","状态","是否为管理员","渠道经理"};
                headerList.add(header);

                List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据
                List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
                for(PartnerInfoDto imp : impList){
                    Map<String, String> map = new HashMap<String, String>();
                    map.put(header[0], imp.getDepartmentName());
                    map.put(header[1], imp.getAccountName());
                    map.put(header[2], imp.getPhone());
                    map.put(header[3], imp.getRoleName());
                    map.put(header[4], MechanismStatusEnum.getByNo(imp.getStatus()).getDes());
                    map.put(header[5], "0".equals(imp.getAccountType())?"是":"否");
                    map.put(header[6],imp.getPrincipalName());
                    mapList.add(map);
                }
                list.add(mapList);
                resDto.setExportPartnerList(list);
            }else{
                //当数据没有时，重定向到原页面，并给出提示
            	resDto.setExportPartnerList(null);
            }
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (YIXUNUNCheckedException e) {
            logger.error("PersonnelServiceImpl ==> exportPartner YIXUNUNCheckedException: {}: ",e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg(e.getCode()+":"+e.getOutMsg());
        }catch (Exception e) {
            logger.error("PersonnelServiceImpl ==> exportPartner error: {}: ",e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("下载合作机构信息失败");
        }
        return resDto;
    }

    @Override
    public Integer selectPartnerCountByCompanyId(Long merchentId) {
        return partnerInfoMapper.selectByCompany(merchentId);
    }


    //获取最后一条验证码
    private boolean isValidate(String phone,String code,String domain,String systemId,String companyUuid){
        //取最新 的那一条
        boolean flag = false;
        List<ValidateCode> list = validateCodeMapper.selectForPwd(phone,systemId,domain,companyUuid);
        if(list != null && list.size() > 0){
            if(list.get(0).getValidateCode().equals(code)){
                flag = (System.currentTimeMillis() - (list.get(0).getCreateTime()).getTime()) / 1000 < 180;
                if(!flag){
                    throw new TServerException("验证码已过期，请重新获取");
                }
            }
        }
        return flag;
    }
    /**
     * 根据域名查询用户是否存在
     * @author sangtao
     * @param domain
     * @param phone
     * @return
     */
    public PartnerInfo getPartnerInfo(String domain,String phone,String systemId){
        List<PartnerInfo> list =  partnerInfoService.getRegisterPartner(domain,phone,systemId);
        if(list != null && list.size() > 0){
            return list.get(0);
        }else{
            return null;
        }
    }
    ///////////////////////////////////////////获取机构人员///////////////////////////////////////////////////////
    //获取部门及其子部门id集合
    private List<Long> getDeptIds(List<Department> department){
        List<Long> res = new ArrayList<Long>();
        getChildDept(res,department);
        return res;
    }
    //获取部门及其子部门id集合
    private List<Long> getDeptIds(Department department){
        List<Long> res = new ArrayList<Long>();
        if(department!=null){
            getChildDept(res,department);
        }
        return res;
    }
    private List<Long> getChildDept(List<Long> res,Department department){
        res.add(department.getId());
        DepartmentDto dto = new DepartmentDto();
        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        dto.setParentId(department.getId());
        dto.setMerchantId(department.getMerchantId());
        List<Department> depart = departmentDao.selectListByDto(dto);
        for(Department dept:depart){
            return getChildDept(res,dept);
        }
        return res;
    }
    private List<Long> getChildDept(List<Long> res,List<Department> department){
        for(Department dept:department){
            res.add(dept.getId());
            DepartmentDto dto2 = new DepartmentDto();
            dto2.setDelFlag(DelFlagEnum.UNDEL.getNo());
            dto2.setParentId(dept.getId());
            dto2.setMerchantId(dept.getMerchantId());
            List<Department> depart2 = departmentDao.selectListByDto(dto2);
            for(Department dep:depart2){
                res.add(dep.getId());
            }
            return getChildDept(res,depart2);
        }
        return res;
    }
    /**
     * 2017.9.25新增需求，
     * 对接人只能看自己对接的合作机构
     * 管理员可以看所有的合作机构
     */
    private List<Long> getDepartmentIds(Long devCompanyid, Long id) {
        //根据登陆人信息查询所有合作机构
        CompanyRelationDto crDto = new CompanyRelationDto();
        crDto.setDevCompany(devCompanyid);
        crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
        crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
        StringBuilder sb = new StringBuilder();
        if(null != crList && crList.size() > 0){
            for(CompanyRelation cr : crList){
                sb.append(cr.getAgentCompany() + ",");
            }
        }

        String merchantIds = sb.toString();
        if(StringUtils.isNotBlank(merchantIds)){
            merchantIds = merchantIds.substring(0, merchantIds.length()-1);
        }else{//没有合作机构
            return null;
        }

        //获取开发商的所有合作机构
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setMerchantIds(merchantIds);
        departmentDto.setOrders("create_time desc");
        List<DepartmentDto> deptList = departmentDao.selectList(departmentDto);

        List<DepartmentDto> returnList = new ArrayList<DepartmentDto>();
        Map<Long, Long> map = new HashMap<Long, Long>();
        Set<DepartmentDto> set = new HashSet<DepartmentDto>();
        Map<Long, Long> parentMap = new HashMap<Long, Long>();
        //非管理员  查出对接人是他自己的
        for (DepartmentDto d : deptList) {
            if (id.equals(d.getPrincipal())) {
                //目前是所有对接人的直属部门
                // todo 查询所有的子部门以及他的父级部门
//				map.put(d.getParentId(), d.getId());
                map.put(d.getId(), d.getParentId());
            }
        }

        // 查询所有的子部门
        for (DepartmentDto d : deptList) {
            // 添加自己
            if (map.containsKey(d.getId())) {
                set.add(d);
            }

            //查询此节点的所有子节点
            if (map.containsKey(d.getParentId())) {
                set.add(d);
                parentMap.put(d.getId(),d.getId());
            }
        }
        //第三层
        for (DepartmentDto d : deptList) {
            if (parentMap.containsKey(d.getParentId())) {
                set.add(d);
            }
        }
        returnList.addAll(set);
        List<Long> list =new ArrayList<Long>();
        for(DepartmentDto d : returnList){
            list.add(d.getId());
        }
        return list;
    }


    private List<Long> getDepartmentIds(Long devCompanyid,Long id,List<Long> ids) {
        //根据登陆人信息查询所有合作机构
        CompanyRelationDto crDto = new CompanyRelationDto();
        crDto.setDevCompany(devCompanyid);
        crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
        crDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
        StringBuilder sb = new StringBuilder();
        if(null != crList && crList.size() > 0){
            for(CompanyRelation cr : crList){
                sb.append(cr.getAgentCompany() + ",");
            }
        }

        String merchantIds = sb.toString();
        if(StringUtils.isNotBlank(merchantIds)){
            merchantIds = merchantIds.substring(0, merchantIds.length()-1);
        }else{//没有合作机构
            return null;
        }

        //获取开发商的所有合作机构
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setMerchantIds(merchantIds);
        departmentDto.setOrders("create_time desc");
        List<DepartmentDto> deptList = departmentDao.selectList(departmentDto);

        Map<Long, DepartmentDto> map = new HashMap<Long, DepartmentDto>();

        //非管理员  查出对接人是他自己的
        // 查询出权限分配的账号Id
// 		List<Long> deptIds = deptPermissionService.getPartnerDeptPermission(id);
// 		if(CollectionUtils.isEmpty(deptIds)) {
// 			return deptList;
// 		}
 		
        for (DepartmentDto department : deptList) {
            if (id.equals(department.getPrincipal())) {
                //目前是所有对接人的直属部门
                map.put(department.getId(), department);
            }
        }

        // 过滤对接人是本人的部门id
        List<Long> list = new ArrayList<Long>();
        if(ids.size() > 0) {
        	for(Long d : ids){
                if(map.containsKey(d)){
                    list.add(d);
                }
            }
        }else {
        	for (Long key : map.keySet()) {
        		list.add(key);
        	}
        }

        return list;
    }

    ///////////////////////////////////////////获取机构人员///////////////////////////////////////////////////////

    //判断上传的附件是否是excel
    public boolean isExcel(String suffix){
        boolean flag = false;
        StringBuffer sb = new StringBuffer();
        //将后缀名统一改为小写
        for(int i=0;i<suffix.length();i++){
            char c = suffix.charAt(i);
            sb.append(Character.toLowerCase(c));
        }
        if("xls|xlsx".indexOf(sb.toString()) > 0){
            flag = true;
        }
        return flag;
    }

	@Override
	public GetPartnerDetailResDto getPartnerDetail(GetPartnerDetailReqDto reqDto) {
		GetPartnerDetailResDto resDto = new GetPartnerDetailResDto();
		PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getId()));
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setPartnerInfo(pi);
		return resDto;
	}

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RegistResDto regist(RegistReqDto registReqDto) throws Exception {
        RegistResDto resDto = new RegistResDto();
        resDto.setResult(ResultEnum.FAIL.getNo());
        boolean flag = true;
        CompanyDto companyDto = new CompanyDto();
        companyDto.setCompanyCode(registReqDto.getCompanyCode());
        if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(registReqDto.getLoginType())){
            flag = validateCodeService.isValidate(registReqDto.getPhone(),registReqDto.getVerificationCode());
        }
        if(flag){
            String loginType = registReqDto.getLoginType();
            String cooCompanyId = "";
            if(StringUtils.isNotBlank(registReqDto.getCompanyCode())){
                cooCompanyId = registReqDto.getCompanyCode().toUpperCase();
            }else{
                resDto.setResultMsg("请输入正确的公司码");
                return resDto;
            }
            // 通过分销公司码转出开发商公司
            if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType) || SystemIdEnum.AGENCY_h5.getCode().equals(loginType)){
                String companyUuid = companyService.getDevCompanyByAgentCompanyCode(cooCompanyId);
                if(StringUtils.isBlank(companyUuid)){
                    resDto.setResultMsg("请输入正确的公司码");
                    return resDto;
                }
                ThreadLocalContainer.Regesiter.COMPANY_UUID.set(companyUuid);
                registReqDto.setCompanyUuid(companyUuid);
            }

            Company agentCompany = companyService.selectByDto(companyDto);
            String ifOpenSysMsg = "0";
            if(Objects.nonNull(agentCompany)){
                ifOpenSysMsg = agentCompany.getIfOpenSysMsg();
            }

            /**
             * 判断是否要暂停当前分销机构的经纪人注册
             */
            if ("0".equals(ifOpenSysMsg)) {
                resDto.setResultMsg("该机构已暂停注册,请更换其他机构注册");
                return resDto;
            }

            //判断该域名下账号是否存在
            List<PartnerInfo> list =  partnerInfoService.getRegisterPartner(registReqDto.getDomain(),registReqDto.getPhone(),registReqDto.getCompanyUuid());
            if(list !=null && list.size() > 0){
                resDto.setResultMsg("您的帐号已存在或在注册审核中");
                return resDto;
            }
            PartnerInfoDto infoDto = new PartnerInfoDto();
            infoDto.setPhone(registReqDto.getPhone());
            infoDto.setDomain(registReqDto.getDomain());
            infoDto.setAccountName(registReqDto.getAccountName());
            infoDto.setCompanyCode(registReqDto.getCompanyCode());
            infoDto.setRegisterPwd(registReqDto.getRegisterPwd());
            if(StringUtil.isNotNull(registReqDto.getMendian())) {
            	infoDto.setDeptId(Long.valueOf(registReqDto.getMendian()));
            }
            if(StringUtil.isNotNull(registReqDto.getZubie())) {
            	infoDto.setDeptId(Long.valueOf(registReqDto.getZubie()));
            }
            infoDto.setQrcodeOriginPartnerId(registReqDto.getQrcodeOriginPartnerId());
            // 分销小程序不需要下发短信。 add by liu.zilong
            if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType)){
            	infoDto.setSystemId(loginType);
            	infoDto.setCheckStatus("1".equals(agentCompany.getEnablePartnerCheck())? 
            			CheckStatusEnum.TODO.getNo(): CheckStatusEnum.NOT_REQUIRED.getNo());
            	// 分销小程序，传递注册模板信息
            }
            // 分销小程序不需要下发短信。 add by liu.zilong
            //公司的
            Map<String,String> resultMap = partnerInfoService.bindPartner(infoDto,registReqDto.getCompanyUuid());
            if("success".equals(resultMap.get("result"))){
                resDto.setResult(ResultEnum.SUCCESS.getNo());
                resDto.setResultMsg(resultMap.get("msg"));
            }else{
                resDto.setResult(ResultEnum.FAIL.getNo());
                resDto.setResultMsg(resultMap.get("msg"));
            }
        }else{
            resDto.setResultMsg("短信验证码错误");
        }

        return resDto;
    }

	@Override
	public InitPasswordResDto initPassword(InitPasswordReqDto reqDto)
			throws Exception {
		InitPasswordResDto res = new InitPasswordResDto();
		PartnerInfo pi = partnerInfoService.selectById(reqDto.getId());
		//生成随机密码
		String password = PasswordUtil.generateRandomNumPwd(8);
		Long userId = reqDto.getId();
		if (userId!= null) {
			PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
			partnerInfoDto.setId(reqDto.getId());
			partnerInfoDto.setPassword(PasswordUtil.md5Hex(password));
			partnerInfoService.update(partnerInfoDto);

			String smsSwitch = smsUtil.getSmsSwitch();
			if(org.apache.commons.lang.StringUtils.isNotEmpty(smsSwitch) && "T".equals(smsSwitch)){
				//发送短信
				String smsTemp = SMSTypeEnum.TYPE_12.getNo();
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDicType(smsTemp);
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if(null != dic){
					String cusName = pi.getAccountName();
					String mobile = pi.getPhone();
					//短信发送的开发商公公司
					Long companyId = 0L;
					CompanyRelationDto crDto = new CompanyRelationDto();
					crDto.setAgentCompany( pi.getHigherid());
					crDto.setRelationStatus(RelationStatusEnum.VALID.getNo());
					List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
					if(null != crList && crList.size() > 0){
						CompanyRelation cr = crList.get(0);
						companyId = cr.getDevCompany();
					}
					String smsContent = dic.getDicValue();
					smsContent = String.format(smsContent, cusName, password);
                    //获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
                    Map<String, String> smsSettingMap = null;
//                	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, companyId,null);
                	Map<String,String> qfSmsMap = new HashMap<>();
                	qfSmsMap.put("key1",pi.getAccountName());
                	qfSmsMap.put("key2",password);
                    Map<String, Object> returnMap = smsUtil.sendMessage(smsContent, mobile, QfSmsTemplateEnum.SMS_RESET_PWD.getId(), smsSettingMap,qfSmsMap);
                    boolean sendStatus = (Boolean) returnMap.get("sendStatus");
                    String sendRes = String.valueOf(returnMap.get("sendRes"));
					SmsHistoryDto smsHis = new SmsHistoryDto();
					smsHis.setSender(smsUtil.getUserName());
					if(null != smsSettingMap) {
        				smsHis.setSender(smsSettingMap.get("userName"));
        			}
					smsHis.setReceiver(mobile);
					smsHis.setContent(smsContent);
					smsHis.setSendStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
                    smsHis.setSendRes(sendRes);
					smsHis.setMerchantId(companyId);
					smsHis.setRemark("修改密码: 中介PC,重置密码");
					smsHis.setCreateUserId(pi.getId());
                    if(returnMap.containsKey("orderUuid")){
                        smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
                    }
                    if(returnMap.containsKey("platform")){
                        smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
                    }
					smsHistoryService.create(smsHis);
				}
			}

			res.setResultMsg(password);
			res.setResult(ResultEnum.SUCCESS.getNo());
		} else {
			res.setResultMsg("初始化密码失败!");
			res.setResult(ResultEnum.FAIL.getNo());
		}
		return res;
	}

	/**
	*@description 人员转移部门
	*@author sangtao
	*@date 2017/12/20
	*@param dto
	**/
	@Override
	public UserChangeDeptResDto userChangeDept(UserChangeDeptReqDto dto){
        UserChangeDeptResDto resDto = new UserChangeDeptResDto();
        PartnerInfo partnerInfo = new PartnerInfo();
        partnerInfo.setId(dto.getPartnerId());
        partnerInfo.setDeptId(dto.getAcceptId());
        int i = partnerInfoMapper.edit(partnerInfo);
        if(i > 0){
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        }else{
            resDto.setResult(ResultEnum.FAIL.getNo());
        }

        dataPermissionService.cleanCompanyCacheByPartner(dto.getPartnerId());
        return resDto;
    }

    @Override
    public ForgetPwdResDto forgetPwd(ForgetPwdReqDto dto) {
        ForgetPwdResDto forgetPwdResDto = new ForgetPwdResDto();
        //生成8位随机密码
        String password = dto.getNewPwd();
        //验证码
        boolean flag = isValidate(dto.getPhone(),dto.getCode(),dto.getDomain(),dto.getLoginType(),dto.getCompanyUuid());
        //验证成功
        if(flag){
            PartnerInfo user = getPartnerInfo(dto.getDomain(),dto.getPhone(),dto.getCompanyUuid());
            if(user != null){
                PartnerInfoDto editInfo = new PartnerInfoDto();
                editInfo.setId(user.getId());
                editInfo.setPassword(PasswordUtil.md5Hex(password));
                partnerInfoService.update(editInfo);
                forgetPwdResDto.setResult(ResultEnum.SUCCESS.getNo());
                forgetPwdResDto.setResultMsg("密码重置成功，密码已重置为："+password);
                //todo 将该条验证码设置无效
            }else{
                forgetPwdResDto.setResult(ResultEnum.FAIL.getNo());
                forgetPwdResDto.setResultMsg("账号不存在或已禁用");
            }
        }else{
            forgetPwdResDto.setResult(ResultEnum.FAIL.getNo());
            forgetPwdResDto.setResultMsg("验证码错误");
        }
        return forgetPwdResDto;
    }

    //根据域名查询公司
    private Company getCompanyByDomain(String domain,String companyUuid){
        CompanyDto cDto = new CompanyDto();
        // todo 审核条件去掉
        //cDto.setStatus("1");//审核状态：0待审核1审核通过2审核失败
        if(StringUtils.isNotEmpty(companyUuid)){
            cDto.setCompanyUuid(companyUuid);
        }else{
            cDto.setDomain(domain);

        }
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<Company> lists = companyService.selectListByDto(cDto);
        if(lists.size() > 0){
            return lists.get(0);
        }else{
            return null;
        }
    }

}
